#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <error.h>
#define PORT 8888
#define SERVER_IP "172.23.232.7"
#define LISTEN_BYTES 128
#define MASSAGE_SIZE 64

int main()
{
    /*构建客户端步骤*/
    /*第一步socket函数*/
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket error");
        exit(-1);
    }

    /*第二步：connect函数*/
    struct sockaddr_in clientAddr;
    memset(&clientAddr, 0, sizeof(clientAddr));
    /*处理函数参数*/
    clientAddr.sin_family = AF_INET;
    clientAddr.sin_port = htons(PORT);
    int ret = inet_pton(AF_INET, SERVER_IP, (void *)&clientAddr.sin_addr.s_addr);
    if (ret == -1)
    {
        perror("inet_pton error");
        exit(-1);
    }
    ret = connect(sockfd, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
    if (ret == -1)
    {
        perror("connect error");
        exit(-1);
    }
    /*发送的数据*/
    char sendMessage[MASSAGE_SIZE];
    memset(sendMessage, 0, sizeof(sendMessage));
    strncpy(sendMessage, "123", sizeof(sendMessage) - 1);

    /*接受的数据*/
    char recvMessage[MASSAGE_SIZE];
    memset(recvMessage, 0, sizeof(recvMessage));
    /*connect三个参数：sockfd;客户端的ip，端口，协议；第二个参数大小*/

    
    while (1)
    {
        /*第三步：通信*/
        ret = write(sockfd, sendMessage, sizeof(sendMessage));
        if (ret == -1)
        {
            perror("write error");
            exit(-1);
        }

        ret = read(sockfd, recvMessage, sizeof(recvMessage));
        if (ret <= 0)
        {
            perror("read error");
            break;
        }
        else
        {
            printf("severMessage=%s\n", recvMessage);
        }

        
        sleep(2);
    }

    /*第四步：关闭套接字*/
    close(sockfd);
    return 0;
}